package vip.finance.makemoney.config;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import vip.finance.makemoney.common.RestEnum;
import vip.finance.makemoney.common.vo.UserInfo;
import vip.finance.makemoney.config.exception.BusinessException;
import vip.finance.makemoney.entity.User;
import vip.finance.makemoney.entity.UserTrade;
import vip.finance.makemoney.mapper.UserTradeMapper;
import vip.finance.makemoney.service.impl.RedisService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author yangbin
 * @since 2023-01-19
 */
@Component
public class UserContextManager {
    private static final String TOKEN_HEADER = "Authorization";
    private static final String TOKEN_START = "Bearer ";
    private static final String TOKEN_REDIS_KEY = "make-money:token:{}";
    @Resource
    private RedisService redisService;
    @Resource
    private UserTradeMapper userTradeMapper;

    /**
     * 获取用户上下文信息
     *
     * @param request
     * @return
     */
    public UserInfo getUserContext(HttpServletRequest request) {
        String userToken = getHeaderToken(request, TOKEN_HEADER);
        if (StringUtils.hasLength(userToken)) {
            // 从缓存或者第三方获取用户信息
            return redisService.getUserInfo(StrUtil.format(TOKEN_REDIS_KEY, userToken));
        }
        throw new BusinessException(RestEnum.LOGIN_INVALID);
    }

    private String getHeaderToken(HttpServletRequest request, String key) {
        String authHeader = request.getHeader(key);
        if (authHeader != null && authHeader.startsWith(TOKEN_START)) {
            // The part after "Bearer "
            return authHeader.substring(TOKEN_START.length());
        }
        return null;
    }

    /**
     * 保存用户上下文信息
     *
     * @return
     */
    public UserInfo saveUserContext(User user) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getUsername());
        userInfo.setName(user.getName());
        userInfo.setMobile(user.getMobile());
        userInfo.setEmail(user.getEmail());
        userInfo.setToken(UUID.randomUUID().toString());
        userInfo.setCookieList(new ArrayList<>());
        List<UserTrade> userTrades = userTradeMapper.selectList(Wrappers.<UserTrade>lambdaQuery().eq(UserTrade::getUserId, user.getId()));
        userTrades.forEach(
                item -> {
                    UserInfo.EastMoneyCookie eastMoneyCookie = new UserInfo.EastMoneyCookie();
                    eastMoneyCookie.setUserTradeId(item.getId());
                    eastMoneyCookie.setAccountId(item.getAccountId());
                    userInfo.getCookieList().add(eastMoneyCookie);
                }
        );
        //今晚token过期
        long timeout = DateUtil.between(new Date(), DateUtil.endOfDay(new Date()), DateUnit.SECOND);
        // redis缓存
        redisService.saveUserInfo(StrUtil.format(TOKEN_REDIS_KEY, userInfo.getToken()), userInfo, timeout, TimeUnit.SECONDS);
        return userInfo;
    }

    public void saveUserContext(UserInfo userInfo) {
        //今晚token过期
        long timeout = DateUtil.between(new Date(), DateUtil.endOfDay(new Date()), DateUnit.SECOND);
        redisService.saveUserInfo(StrUtil.format(TOKEN_REDIS_KEY, userInfo.getToken()), userInfo, timeout, TimeUnit.SECONDS);
    }
}
